package com.css.security.core.authorization;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * CssAuthorizeConfigManager
 * 默认的授权配置管理器
 *
 * @author hanyx
 * @date 2019/04/18
 */
@Component
public class CssAuthorizeConfigManager implements AuthorizeConfigManager {

    /**
     * 有序集合
     */
    @Autowired
    private List<AuthorizeConfigProvider> authorizeConfigProviders;


    /**
     * @param config
     */
    @Override
    public void config(ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry config) {
        String existAnyRequestConfigName = null;
        int count = 0;

        for (AuthorizeConfigProvider authorizeConfigProvider : authorizeConfigProviders) {
            boolean currentIsAnyRequestConfig = authorizeConfigProvider.config(config);
            if (currentIsAnyRequestConfig) {
                count++;
                existAnyRequestConfigName = existAnyRequestConfigName + "," + authorizeConfigProvider.getClass().getSimpleName();
            }
        }

        if (count > 1) {
            existAnyRequestConfigName = StringUtils.substringAfter(existAnyRequestConfigName, "null,");
            throw new RuntimeException("重复的anyRequest配置:" + existAnyRequestConfigName);
        }

        /**
         * 只有所有的配置中都没有针对anyRequest的配置时添加
         */
        if (count == 0) {
            config.anyRequest().authenticated();
        }
    }
}
